package main

import (
	"net/http"
	"log"
	"os"
	"strings"
	"io"
	"fmt"
	"github.com/nofuck/reports/utils"
	"path"
	"github.com/nofuck/reports/generator"
)

var uploadPath, compressPath, generatorPath string
var port int

func init() {
	gopath := os.Getenv("GOPATH")
	uploadPath = gopath + "/data/upload-file"
	compressPath = gopath + "/data/compress"
	generatorPath = gopath + "/data"
	port = 8081
}

type Data interface {
}

type Message struct {
}

type Response struct {
	Code    int       `json:"code"`
	Message string    `json:"message"`
	Data    Data    `json:"data"`
}

type UploadInfo struct {
	Path     string `json:"path"`
	FileName string `json:"file_name"`
}

func main() {
	fmt.Println("Starting and listen 8081 success ......")
	http.HandleFunc("/upload", uploadFile)
	err := http.ListenAndServe(":8081", nil)
	if err != nil {
		log.Fatal("Listen and serve error", err.Error())
		return
	}
}

func uploadFile(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case "POST":
		file, handler, err := r.FormFile("file")
		if err != nil {
			log.Fatal("Form file:", err.Error())
			w.Write([]byte("Form file" + err.Error()))
		}
		defer file.Close()
		defer func() {
			if err := file.Close(); err != nil {
				log.Fatal("Close:", err.Error())
				w.Write([]byte("Close error:" + err.Error()))
			}
		}()

		fullFileName := path.Base(handler.Filename)
		suffix := path.Ext(fullFileName)
		newFileName := utils.RandStr(16) + suffix
		names := []string{uploadPath, newFileName}
		f, err := os.Create(strings.Join(names, "/"))
		if err != nil {
			log.Fatal("Create file error:", err.Error())
			w.Write([]byte("Create file error:" + err.Error()))
		}
		defer f.Close()
		io.Copy(f, file)

		unzipPath, err := utils.UnZip(uploadPath+"/"+newFileName, compressPath)
		report := generator.XlsxReport{}
		xlsxName, _ := report.CreateXlsx(unzipPath, generatorPath)
		w.Header().Add("Content-Disposition", fmt.Sprintf("attachment; filename=%s", path.Base(xlsxName)))
		w.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
		http.ServeFile(w, r, xlsxName)
	}
}
